import { createWebHistory, createRouter, RouteRecordRaw } from 'vue-router';
import { User } from '../types/user';
import { useUserStore } from '../store';

// === 静态路由 ===
const staticRoutes: RouteRecordRaw[] = [
    {
        path: '/',
        name: "home",
        component: () => import('../components/index/index.vue'),
        meta: { title: '首页', requiresAuth: true },
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('../components/login/login.vue'),
        meta: { title: '登录', requiresAuth: false }
    },
    {
        path: '/register',
        name: 'Register',
        component: () => import('../components/register/register.vue'),
        meta: { title: '注册', requiresAuth: false }
    },
    {
        path: '/forgot',
        component: () => import('../components/forgotpassword/forgotpass.vue'),
        meta: { title: '忘记密码', requiresAuth: false }
    },
    {
        path: '/401',
        component: () => import('../components/error/unAuth.vue'),
        meta: { title: '401', requiresAuth: false }
    },
    {
        path: '/404',
        name: '404',
        component: () => import('../components/error/unfind.vue'),
        meta: { title: '404', requiresAuth: false }
    },
    {
        path: '/:pathMatch(.*)*',
        redirect: '/404'
    }
];

// === 动态路由模板（按权限加载） ===
const asyncRoutes: RouteRecordRaw[] = [
    {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('../components/dashboard/dashboard.vue'),
        meta: { title: '仪表盘', requiresAuth: true, route: 2 }
    },
    {
        path: 'user/info',
        name: 'UserInfo',
        component: () => import('../components/user/userinfo.vue'),
        meta: { title: '用户信息', requiresAuth: true, route: 3 }
    },
    {
        path: 'user/edit',
        name: 'UserEdit',
        component: () => import('../components/user/useredit.vue'),
        meta: { title: '用户编辑', requiresAuth: true, route: 4 }
    },
    {
        path: 'user/list',
        name: 'UserList',
        component: () => import('../components/user/userlist.vue'),
        meta: { title: '用户列表', requiresAuth: true, route: 5 }
    },
    {
        path: 'user/add',
        name: 'UserAdd',
        component: () => import('../components/user/useradd.vue'),
        meta: { title: '用户添加', requiresAuth: true, route: 6 }
    }
];

const router = createRouter({
    history: createWebHistory(),
    routes: staticRoutes
});

let dynamicRoutesAdded = false;

// 动态添加路由
export const registerRoutes = async (): Promise<void> => {
    if (dynamicRoutesAdded) return;

    const store = useUserStore();
    let user = JSON.parse(sessionStorage.getItem("user") || "null") as User;
    if (!user) {
        await store.fetchUserInfo(0);
        user = store.user;
    }

    if (!user || !user.auth || !Array.isArray(user.auth.route)) {
        console.warn("用户信息或权限不完整，无法加载动态路由");
        return;
    }

    const routes = user.auth.route;
    const matchedRoutes = asyncRoutes.filter(item => routes.includes(item.meta?.route as number));

    if (matchedRoutes.length > 0) {
        matchedRoutes.forEach(route => {
            router.addRoute('home', route);  // 'home' 必须和静态路由name匹配
        });
        sessionStorage.setItem("routerMap", JSON.stringify(matchedRoutes));
        dynamicRoutesAdded = true;
        console.log('✅ 动态路由注册成功');
    } else {
        console.warn('⚠️ 未匹配到任何可用动态路由');
    }
};
let triedRedirectDashboard = false; // 标记是否尝试过跳转到 dashboard
router.beforeEach(async (to, from, next) => {
    const token = sessionStorage.getItem('token');

    if (!token) {
        if (to.path === '/login' || to.path === '/register') return next();
        return next('/login');
    }

    if (to.path === '/login') return next('/dashboard');

    if (!dynamicRoutesAdded) {
        await registerRoutes();
        return next({ ...to, replace: true });
    }
    // 访问404页面时，尝试跳转到/dashboard（只尝试一次）
    if (to.path === '/404') {
        if (!triedRedirectDashboard) {
            triedRedirectDashboard = true;
            console.log(from)
            let uPath = sessionStorage.getItem("beforePath");
            let a = uPath && uPath !== "" ? uPath : '/dashboard';
            return next(a);
        } else {
            // 已经尝试过跳转dashboard，仍然404，显示404页面
            triedRedirectDashboard = false; // 重置状态，避免影响下次访问
            return next();
        }
    } else {
        sessionStorage.setItem("beforePath", to.path)
    }
    if (to.path === '/') return next('/dashboard');
    next();
});
export default router;
